package com.springboot.chapter4.jdbc;

import com.springboot.chapter4.pojo.User;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * 作者：paopao
 * 版本：1.0
 */
public class UserService {

    public int insertUser() {
        UserDao userDao = new UserDao();
        User user = new User();
        user.setUserName("paopao");
        user.setNote("paopao is a good boy");
        Connection conn = null;
        int result = 0;
        try {
            // 获取数据库事务连接
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/chapter", "root", "123456"
            );
            // 非自动提交事务
            conn.setAutoCommit(false);
            result = userDao.insertUser(conn, user);
            // 提交事务
            conn.commit();
        } catch (Exception e) {
            // 回滚事务
            try {
                conn.rollback();
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
            throw new RuntimeException(e);
        } finally {
            if(conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return result;
    }

}
